<template>
  <div class="article-edit-container">
    <!-- 标题输入 -->
    <div class="form-item">
      <label for="title">标题</label>
      <input id="title" v-model="article.title" placeholder="请输入文章标题" />
    </div>

    <!-- 内容编辑 -->
    <div class="form-item">
      <label for="content">内容</label>
      <textarea id="content" v-model="article.content" placeholder="请输入文章内容"></textarea>
    </div>

    <!-- 发布按钮 -->
    <div class="actions">
      <button @click="publishArticle">发布</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      article: {
        title: '',
        psy_id: 1, // 当前用户的 psy_id
        content: '',
      },
    };
  },
  methods: {
    // 发布文章
    async publishArticle() {
  if (!this.article.title || !this.article.content) {
    uni.showToast({ title: '请填写完整信息', icon: 'none' });
    return;
  }

  // 获取当前用户的 psy_id
  this.article.psy_id = uni.getStorageSync('psy_id');

  try {
    const response = await fetch('http://127.0.0.1:5001/api_1_0/article', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        title: this.article.title,
        psy_id: this.article.psy_id,
        content: this.article.content
      }),
    });

    if (response.ok) {
      uni.showToast({ title: '发布成功', icon: 'none' });
      this.article = { title: '', psy_id: '', content: '' }; // 清空表单
      uni.navigateTo({
         url: '/pages/psy/my/my'
      });
    } else {
      uni.showToast({ title: '发布失败', icon: 'none' });
    }
  } catch (error) {
    console.error('发布文章时出错:', error);
    uni.showToast({ title: '网络错误，稍后再试', icon: 'none' });
  }
}
  },
};
</script>

<style scoped>
.article-edit-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.form-item {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

input,
textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 14px;
}

textarea {
  height: 200px;
  resize: vertical;
}

button {
  padding: 10px 20px;
  background-color: #81b337;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>